package com.iking.toolkit.aop;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 通过Aop拦截  统一打印日志
 */
@Component
@Aspect
@Slf4j
public class CheckAndLogAop {

    @Pointcut("execution(* com.iking.toolkit.*.controller..*.*(..))")
    public void apiLogAop() {
        log.info("apiLogAop");
    }

    private static final String ERROR_LOG ="流水号:{},响应 ===== {}.{}() end =====,响应时间:{}毫秒,响应内容:{}";

    @Around("apiLogAop()")
    public Object aroundApi(ProceedingJoinPoint point) throws Throwable {
        String declaringType = point.getSignature().getDeclaringTypeName();
        String signature = point.getSignature().getName();
        String args = point.getArgs() == null ? "" : JSONUtil.toJsonStr(point.getArgs());
        String busSeq = IdUtil.simpleUUID();
        log.info("流水号:{},请求=={}.{}() start =====,参数:{}",busSeq,declaringType, signature, args);
        TimeInterval timer = DateUtil.timer();
        //执行该方法
        Object response = point.proceed();
        String info =response == null ? "" : JSONUtil.toJsonStr(response);
        log.info(ERROR_LOG, busSeq,point.getSignature().getDeclaringTypeName(), point.getSignature().getName(), timer.interval(), info);
        return response;
    }
}
